package com.example.shujujiegousuanfa.链表;

public class LinkList<T> {
    /**
     * 定义一个链表表头
     */
    public Node<T> first;

    private int pos = 0;

    public LinkList() {
        this.first = null;
    }

    /**
     * 插入一个头结点
     *
     * @param data
     */
    public void insertFront(T data) {
        Node<T> node = new Node<T>(data);
        node.next = this.first;
        this.first = node;
    }

    /**
     * 删除一个头结点,并返回头结点
     *
     * @return
     */
    public Node<T> deleteFront() {
        Node<T> temp = this.first;
        this.first = temp.next;
        return temp;
    }

    /**
     * 在指定位置之后插入结点
     *
     * @param index
     * @param data
     */
    public void insertNode(int index, T data) {
        Node<T> node = new Node<T>(data);
        Node<T> current = this.first;
        Node<T> previous = this.first;
        while (pos != index) {
            previous = current;
            current = current.next;
            pos++;
        }
        node.next = current;
        previous.next = node;
        pos = 0;
    }

    /**
     * 在删除任意位置的节点
     *
     * @param index
     * @return
     */
    public Node<T> deleteNode(int index) {
        Node<T> current = this.first;
        Node<T> previous = this.first;
        while (pos != index) {
            previous = current;
            current = current.next;
            pos++;
        }

        if (current == this.first) {
            this.first = this.first.next;
        } else {
            previous.next = current.next;
            pos = 0;
        }

        return current;
    }

    /**
     * 根据结点数据删除结点（仅删除第一个）
     */
    public Node<T> deleteFirstData(T data) {
        Node<T> current = this.first;
        Node<T> previous = this.first;
        while (current.data != data) {
            previous = current;
            current = current.next;
        }

        if (current == this.first) {
            this.first = this.first.next;
        } else {
            previous.next = current.next;
        }

        return current;
    }

    /**
     * 根据结点数据查找结点(仅查找第一个)
     *
     * @param data
     * @return
     */
    public Node<T> findFirstData(T data) {
        Node<T> current = this.first;
        while (current.data != data) {
            if (current.next == null)
                return null;
            current = current.next;
        }

        return current;
    }

}

